#define _CRT_SECURE_NO_WARNINGS 1
#include"BinaryTree.h"
#include"Queue.h"

BTNode* BuyNode(int x)
{
	BTNode* new = (BTNode*)malloc(sizeof(BTNode));
	if (new == NULL)
	{
		perror("malloc fail");

		return 0;
	}
	new->_data = x;
	new->_left = NULL;
	new->_right = NULL;
	return new;
}

BTNode* BinaryTreeCreate()
{
	BTNode* n1 = BuyNode(1);
	BTNode* n2 = BuyNode(2);
	BTNode* n3 = BuyNode(3);
	BTNode* n4 = BuyNode(4);
	BTNode* n5 = BuyNode(5);
	BTNode* n6 = BuyNode(6);

	n1->_left = n2;
	n1->_right = n4;
	n2->_left = n3;
	n2->_right = n5;
	n4->_left = n6;

	return n1;
}

void BinaryTreeDestory(BTNode* root)
{
	if (root == NULL)
		return;
	BinaryTreeDestory(root->_left);
	BinaryTreeDestory(root->_right);

	free(root);
}

int BinaryTreeSize(BTNode* root)
{
	return root == NULL ? 0 : 
		BinaryTreeSize(root->_left) 
		+ BinaryTreeSize(root->_right)+1;
}

void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL) {
		printf("N");
		return;
	}
	printf("%d ", root->_data);
	BinaryTreePrevOrder(root->_left);
	BinaryTreePrevOrder(root->_right);
}

void BinaryTreeInOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}
	BinaryTreeInOrder(root->_left);
	printf("%d ", root->_data);
	BinaryTreeInOrder(root->_right);
}

void BinaryTreePostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N");
		return;
	}
	BinaryTreePostOrder(root->_left);
	BinaryTreePostOrder(root->_right);
	printf("%d", root->_data);
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->_left == NULL && root->_right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->_left) 
		+ BinaryTreeLeafSize(root->_right);
}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
		return 0;
	else if (k == 1)
		return 1;
	else if (k > 1)
		return BinaryTreeLevelKSize(root->_left, k - 1) 
		+ BinaryTreeLevelKSize(root->_right, k - 1);
}

BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
		return NULL;
	if (root->_data==x)
		return root;
	BTNode* ret1;
	ret1=BinaryTreeFind(root->_left, x);
	if (ret1)
		return ret1;
	return BinaryTreeFind(root->_right, x);
}

void BinaryTreeLevelOrder(BTNode* root)
{
	Que q;
	Queueinit(&q);
	if (root != NULL)
		Queuepush(&q,root);
	while (!QueueEmpty(&q))
	{
		BTNode* Front = QueueFront(&q);
		Queuepop(&q);
		printf("%d", Front->_data);
		if(Front->_left)
			Queuepush(&q, Front->_left);
		if(Front->_right)
			Queuepush(&q, Front->_right);
	}
	Queuedestroy(&q);
}

int BinaryTreeComplete(BTNode* root)
{
	Que q;
	Queueinit(&q);
	Queuepush(&q, root);
	while (!QueueEmpty(&q))
	{
		BTNode* Front = QueueFront(&q);
		Queuepop(&q);
		if (Front == NULL)
			break;
		Queuepush(&q, Front->_left);
		Queuepush(&q, Front->_right);
	}
	while (!QueueEmpty(&q))
	{
		BTNode* Front = QueueFront(&q);
		Queuepop(&q);
		if (Front != NULL)
			return 0;
	}
	return 1;
}